package m.app.action;

import com.alibaba.fastjson.JSONObject;
import m.appserver.AuthInfoUtil;
import m.base.model.UserInfo;
import m.base.util.PowerUtil;
import m.common.action.ActionMeta;
import m.common.action.RequestMeta;
import m.common.action.VueResult;
import m.common.model.type.FieldType;
import m.common.model.util.ModelQuery;
import m.common.model.util.ModelQueryList;
import m.common.model.util.QueryCondition;
import m.common.model.util.QueryOrder;
import m.store.model.*;
import m.store.service.StockInfoService;
import m.store.service.StoreNumberService;
import m.system.document.DocumentMeta;
import m.system.document.DocumentMethodMeta;
import m.system.document.DocumentParamMeta;
import m.system.exception.MException;
import m.system.util.JSONMessage;
import m.system.util.ObjectUtil;
import m.system.util.StringUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@ActionMeta(name = "app/stockInfo",title = "app入库信息")
public class StockInfoAction extends AppAction{
    private StockInfo model;
    private List<GoodsStockRecord> list;
    private List<GoodsOutRecord> refundList;
    private GoodsStockRecord detail;
    @DocumentMeta(
        method = @DocumentMethodMeta(title = "查询入库列表",permission = true),
        params = {
            @DocumentParamMeta(name = "page.index",description = "分页开始位置",type = FieldType.INT),
            @DocumentParamMeta(name = "page.num",description = "分页每页数量",type = FieldType.INT),
            @DocumentParamMeta(name = "params[oid@eq]",description = "条件示例，字段和操作符中间用@，值为空不添加",type = FieldType.STRING,length = 50),
            @DocumentParamMeta(name = "params[oid#desc]",description = "排序示例，字段和操作符中间用#，值为空不生效",type = FieldType.STRING,length = 50)
        }
    )
    public JSONMessage queryList() throws Exception {
        ModelQueryList queryList=toQueryList(StockInfo.class,"*","guest.*");
        queryList.addCondition(QueryCondition.eq("status",OrderModel.Status_Done));
        queryList.addCondition(QueryCondition.in("type", StockInfo.Type_Stock,StockInfo.Type_Allocate,StockInfo.Type_Refund));
        queryList.addCondition(QueryCondition.not(QueryCondition.eq("oweAmount",0)));
        queryList.addCondition(QueryCondition.eq("store.oid", PowerUtil.getSessionStoreOid()));
        queryList.addCondition(QueryCondition.eq("inputUser.oid", PowerUtil.getSessionUserOid()));
        return JSONMessage.success("查询成功").push("page",ModelQueryList.getModelPageInfo(queryList));
    }
    @DocumentMeta(
        method = @DocumentMethodMeta(title = "我的入库登记列表",permission = true),
        params = {
            @DocumentParamMeta(name = "page.index",description = "分页开始位置",type = FieldType.INT),
            @DocumentParamMeta(name = "page.num",description = "分页每页数量",type = FieldType.INT),
            @DocumentParamMeta(name = "params[oid@eq]",description = "条件示例，字段和操作符中间用@，值为空不添加",type = FieldType.STRING,length = 50),
            @DocumentParamMeta(name = "params[oid#desc]",description = "排序示例，字段和操作符中间用#，值为空不生效",type = FieldType.STRING,length = 50)
        }
    )
    public JSONMessage myList() throws Exception {
        ModelQueryList queryList=toQueryList(StockInfo.class,"*","guest.*");
        queryList.addCondition(QueryCondition.eq("inputUser.oid",PowerUtil.getSessionUserOid()));
        queryList.addCondition(QueryCondition.not(QueryCondition.in("type",StockInfo.Type_Virtual,StockInfo.Type_Server)));
        return JSONMessage.success("查询成功").push("page",ModelQueryList.getModelPageInfo(queryList));
    }
    @DocumentMeta(
        method = @DocumentMethodMeta(title = "入库待审核列表",permission = true),
        params = {
            @DocumentParamMeta(name = "page.index",description = "分页开始位置",type = FieldType.INT),
            @DocumentParamMeta(name = "page.num",description = "分页每页数量",type = FieldType.INT),
            @DocumentParamMeta(name = "params[oid@eq]",description = "条件示例，字段和操作符中间用@，值为空不添加",type = FieldType.STRING,length = 50),
            @DocumentParamMeta(name = "params[oid#desc]",description = "排序示例，字段和操作符中间用#，值为空不生效",type = FieldType.STRING,length = 50)
        }
    )
    public JSONMessage checkList() throws Exception {
        ModelQueryList queryList=toQueryList(StockInfo.class,"*","guest.*");
        queryList.addCondition(QueryCondition.eq("status",OrderModel.Status_Check));
        queryList.addCondition(QueryCondition.eq("store.oid", PowerUtil.getSessionStoreOid()));
        queryList.addCondition(QueryCondition.not(QueryCondition.in("type",StockInfo.Type_Virtual,StockInfo.Type_Server)));
        return JSONMessage.success("查询成功").push("page",ModelQueryList.getModelPageInfo(queryList));
    }
    @DocumentMeta(
        method = @DocumentMethodMeta(title = "获取入库信息",permission = true),
        params = {
            @DocumentParamMeta(name = "model.oid",description = "主键",type = FieldType.STRING,length = 50,notnull = true)
        }
    )
    public JSONMessage getInfo() throws Exception {
        if(null!=model&&!StringUtil.isSpace(model.getOid())){
            model= ModelQueryList.getModel(model,"*","guest.*","inputUser.realname","checkUser.realname");
            PowerUtil.verifyStoreData(model.getStore().getOid());
            list=ModelQueryList.getModelList(GoodsStockRecord.class,new String[]{"*","goods.*"},null,
                    QueryCondition.eq("stock.oid",model.getOid()), QueryOrder.asc("oid"));
            refundList=ModelQueryList.getModelList(GoodsOutRecord.class,new String[]{"*","record.*","record.goods.*"},null,
                    QueryCondition.eq("sale.refundStock.oid",model.getOid()), QueryOrder.asc("oid"));
        }else if(null!=model&& ObjectUtil.notEmptyOid(model.getRefundSale())){
            if(!ModelQueryList.getModelList(StockInfo.class, new String[]{"oid"}, null,
                QueryCondition.and(
                    QueryCondition.eq("refundSale.oid", model.getRefundSale().getOid()),
                    QueryCondition.not(QueryCondition.eq("status", OrderModel.Status_Done))
                )
            ).isEmpty()) throw new MException(this.getClass(),"已存在该订单未完成的退货，请到入库登记里查看。");
            model.setRefundSale(ModelQueryList.getModel(SaleInfo.class,model.getRefundSale().getOid(),"*","guest.*"));
            model.setGuest(model.getRefundSale().getGuest());
            model.setOrderNo(StoreNumberService.getNextStockNumber());
            model.setStatus(OrderModel.Status_Register);
            model.setType(StockInfo.Type_Refund);
            model.setInputUser(PowerUtil.getSessionUser(true));
            model.setInputDate(new Date());
            model.setStockDate(new Date());
            list=new ArrayList<>();
            refundList=new ArrayList<>();
        }else{
            model=new StockInfo();
            model.setOrderNo(StoreNumberService.getNextStockNumber());
            model.setStatus(OrderModel.Status_Register);
            model.setType(StockInfo.Type_Stock);
            model.setInputUser(PowerUtil.getSessionUser());
            model.setInputDate(new Date());
            model.setStockDate(new Date());
            list=new ArrayList<>();
            refundList=new ArrayList<>();
        }
        boolean edit=OrderModel.Status_Register.equals(model.getStatus());
        boolean check=OrderModel.Status_Check.equals(model.getStatus())&& PowerUtil.hasPower(PowerUtil.Stock);
        return JSONMessage.success("查询成功")
                .push("model",model)
                .push("list",list)
                .push("refundList",refundList)
                .push("edit",edit)
                .push("check",check)
                .push("defRepository",PowerUtil.getDefRepository().getOid());
    }
    @DocumentMeta(
        method = @DocumentMethodMeta(title = "获取退货明细信息",permission = true),
        params = {
            @DocumentParamMeta(name = "detail.oid",description = "主键",type = FieldType.STRING,length = 50,notnull = true)
        }
    )
    public JSONMessage getRefund() throws Exception {
        if (null != detail && !ObjectUtil.isEmptyOid(detail.getBackRecord())) {
            detail.setBackRecord(ModelQueryList.getModel(detail.getBackRecord(), "*", "goods.name"));
            //model.setStockNum(model.getBackRecord().getSurplusNum());
            detail.setPrice(detail.getBackRecord().getPreferentialPrice());
            detail.setPreferential(0d);
            detail.setStockAmount(0d);
        } else {
            throw new MException(this.getClass(), "参数错误");
        }
        return JSONMessage.success("查询成功")
                .push("detail",detail);
    }

    public StockInfo getModel() {
        return model;
    }

    public void setModel(StockInfo model) {
        this.model = model;
    }

    public List<GoodsStockRecord> getList() {
        return list;
    }

    public void setList(List<GoodsStockRecord> list) {
        this.list = list;
    }

    public GoodsStockRecord getDetail() {
        return detail;
    }

    public void setDetail(GoodsStockRecord detail) {
        this.detail = detail;
    }

    public List<GoodsOutRecord> getRefundList() {
        return refundList;
    }

    public void setRefundList(List<GoodsOutRecord> refundList) {
        this.refundList = refundList;
    }
}
